<?php

namespace App\Http\Controllers;

use App\Jobs\ChampionshipNotice;
use App\Models\Championship;
use App\Models\ChampionshipUser;
use App\Models\WechatUser;
use Illuminate\Http\Request;

class ChampionshipController extends Controller
{
    function list() {
        $city = request()->input('city', 0);
        $city = rtrim($city, '0');
        if (strlen($city) % 2 === 1) {
            $city = $city . '0';
        }
        $city .= '%';

        $pn = request()->input('pn', config('api.page_num'));
        $list = Championship::where([['status', '>', 10], ['city', 'like', $city]])
            ->select('id', 'title', 'game_datetime', 'signup_datetime', 'address', 'remark', 'status', 'view')
            ->orderBy('game_datetime', 'desc')
            ->paginate($pn);
        return response()->json(['recode' => 1,
            'data' => ['last_page' => $list->lastPage()
                , 'page' => $list->currentPage()
                , 'list' => $list->items()]]);

    }

    public function info()
    {
        $id = request()->input('id', 0);
        $userId = request()->input('user_id', 0);

        $info = Championship::find($id);
        if (!$info) {
            return response()->json(
                [
                    'recode' => 0,
                    'msg' => '未找到详情',
                ]
            );
        }
        //更新观看次数
        $info->view += 1;
        $info->save();

        //查询用户是否已经报名
        $championshipUser = ChampionshipUser::where([
            ['championship_id', $id],
            ['user_id', $userId],
            ['status', 20],
        ])
            ->first();
        $isSignup = 0;
        if ($championshipUser) {
            $isSignup = 1;
        }
        //查询报名人员
        $signupList = ChampionshipUser::where([
            ['championship_id', $id],
            ['status', 20],
        ])
            ->select('id', 'user_id')
            ->with('user:id,name,head_img')
            ->limit(5)
            ->get();
        $signupCount = ChampionshipUser::where([
            ['championship_id', $id],
            ['status', 20],
        ])->count();

        return response()->json(
            [
                'recode' => 1,
                'info' => $info,
                'signup' => $isSignup,
                'signup_list' => $signupList,
                'signup_count' => $signupCount,
            ]
        );

    }

    public function startGame()
    {
        $userId = request()->input('user_id', 0);
        $gameDatetime = request()->input('game_datetime');
        $endGameDatetime = request()->input('end_game_datetime');
        $signupDatetime = request()->input('signup_datetime');
        $title = request()->input('title', '');
        $address = request()->input('address', '');
        $signupPrice = request()->input('signup_price', '0');
        $prize = request()->input('prize', '');
        $remark = request()->input('remark', '');

        $userInfo = WechatUser::find($userId);

        if ($userId == 0 || !$userInfo) {
            return response()->json(['recode' => 0, 'msg' => '组织者为空']);
        }
        if ($gameDatetime < $signupDatetime) {
            return response()->json(['recode' => 0, 'msg' => '报名截止时间晚于比赛时间']);
        }
        if ($gameDatetime > $endGameDatetime) {
            return response()->json(['recode' => 0, 'msg' => '比赛开始时间晚于结束时间']);
        }
        if ($title == '') {
            return response()->json(['recode' => 0, 'msg' => '标题不能为空']);
        }
        if ($address == '') {
            return response()->json(['recode' => 0, 'msg' => '地点不能为空']);
        }

        $championship = new Championship;
        $championship->city = $userInfo->city;
        $championship->organizer = $userId;
        $championship->title = $title;
        $championship->game_datetime = $gameDatetime;
        $championship->end_game_datetime = $endGameDatetime;
        $championship->address = $address;
        $championship->signup_datetime = $signupDatetime;
        $championship->signup_price = $signupPrice;
        $championship->prize = $prize;
        $championship->remark = $remark;
        $championship->save();
        //发送通知
        $this->dispatch((new ChampionshipNotice($championship)));

        return response()->json(['recode' => 1, 'id' => $championship->id, 'msg' => '保存成功']);

    }

    public function getChampionshipByUser()
    {
        $pn = request()->input('pn', config('api.page_num'));
        $userId = request()->input('user_id');

        $list = Championship::whereHas('signup', function ($query) use ($userId) {
            $query->where('user_id', $userId);
        })
            ->select('id', 'title', 'game_datetime', 'signup_datetime', 'address', 'remark', 'status', 'view')
            ->orderBy('game_datetime', 'desc')
            ->paginate($pn);
        return response()->json(['recode' => 1,
            'data' => ['last_page' => $list->lastPage()
                , 'page' => $list->currentPage()
                , 'list' => $list->items()]]);
    }
}
